package kids.movies.hoathinhHDSRC.view;

import java.util.ArrayList;

import kids.movies.hoathinhHD.R;
import kids.movies.hoathinhHDSRC.E4KidsConfig;
import kids.movies.hoathinhHDSRC.E4KidsSlidingMenuActivity;
import kids.movies.hoathinhHDSRC.adapter.AlbumIndexFragmentAdapter;
import kids.movies.hoathinhHDSRC.adapter.AlbumIndexFragmentAdapter.IClickPla;
import kids.movies.hoathinhHDSRC.adapter.SlideShowImageAdapter;
import kids.movies.hoathinhHDSRC.adapter.SlideShowImageAdapter.setOnClickItemListener;
import kids.movies.hoathinhHDSRC.adapter.VideoIndexFragmentAdapter.ClickItemVideo;
import kids.movies.hoathinhHDSRC.adapter.VideoIndexFragmentAdapter;
import kids.movies.hoathinhHDSRC.customize.CustomGridView;
import kids.movies.hoathinhHDSRC.customize.NotInterceptInPager;
import kids.movies.hoathinhHDSRC.db.DbSupport;
import kids.movies.hoathinhHDSRC.db.TableDb;
import kids.movies.hoathinhHDSRC.entity.InfoAds;
import kids.movies.hoathinhHDSRC.entity.InfoAlbum;
import kids.movies.hoathinhHDSRC.service.RequestService;
import kids.movies.hoathinhHDSRC.util.Debug;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.bzydroid.network.http.AbsRequestHandler;
import com.bzydroid.network.http.NetworkResponse;
import com.bzydroid.network.http.client.BzydroidHttpClient;
import com.bzydroid.network.http.exception.BzydroidNetworkExeception;
import com.bzydroid.network.http.response.HttpJSONObjectResponse;
import com.bzydroid.utils.BzydroidLog;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.telpoo.frame.net.BaseNetSupportBeta;
import com.telpoo.frame.net.NetConfig;
import com.telpoo.frame.object.BaseObject;
import com.telpoo.frame.utils.JsonSupport;

public class IndexNoTabActivity extends E4KidsSlidingMenuActivity implements
		OnClickListener {

	private ImageView ivABCancelSearch;
	private ImageView ivABSearch;
	private EditText edtABSearch;
	private LinearLayout llContainEdt;
	private ImageView tvABTitle;
	private ImageView ivABLogo;
	private static AdView adView;
	protected ImageLoader imageLoadern = ImageLoader.getInstance();
	protected DisplayImageOptions optionsn;
	private VideoIndexFragmentAdapter adapterVideo;
	private AlbumIndexFragmentAdapter adapterAlbum;
	private SlideShowImageAdapter adapterAds;

	private ArrayList<InfoAlbum> dataPlaylist;

	private NotInterceptInPager viewPager;
	private CustomGridView gvVideo;
	private RelativeLayout rlContainPager;

	private TextView tvTitleVideo;

	private ScrollView scroller;

	private View root;

	private Handler slideHandler;

	private boolean isTouch = false;
	private int pageViewPager;
	private LinearLayout llListCat;
	LayoutInflater mInflater;
	View vListCat;
	TextView tvTitle;
	CustomGridView gvListCat;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_v2_index);

		this.setBehindContentView(R.layout.frame_layout_container);
		// this.getSlidingMenu().setSecondaryMenu(R.layout.frame_right_container);
		this.setDefaultBar();
		configLeftSlideMenu();
		// this.removeSlidingMenu();
		DbSupport.initDb(IndexNoTabActivity.this);
		init();

	}

	private void init() {

		adView = (AdView) findViewById(R.id.ad);
		showAdmod();
		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		vListCat = mInflater.inflate(R.layout.layout_item_cat_index, null);
		tvTitle = (TextView) vListCat.findViewById(R.id.tvTitlePla);
		gvListCat = (CustomGridView) vListCat.findViewById(R.id.gvAlbum);
		ivABCancelSearch = actionBar.getIvABCancelSearch();
		ivABSearch = actionBar.getIvABSearch();
		edtABSearch = actionBar.getEdtABSearch();
		llContainEdt = actionBar.getLlContainEdt();
		ivABLogo = actionBar.getIvABLogo();
		tvABTitle = actionBar.getIvTitle();

		ivABLogo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				toggle();
			}
		});

		ivABSearch.setOnClickListener(this);
		ivABCancelSearch.setOnClickListener(this);

		edtABSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
		edtABSearch.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView arg0, int actionID,
					KeyEvent arg2) {
				String text = edtABSearch.getText().toString().trim();
				if (!text.equals("") || !TextUtils.isEmpty(text)) {

					goActivitySearch(IndexNoTabActivity.this,
							SearchResultActivity.class,
							E4KidsConfig.KEY_INTENT_SEARCH, text);
				}
				return true;
			}
		});

		slideHandler = new Handler();

		viewPager = (NotInterceptInPager) findViewById(R.id.viewpager);

		DisplayMetrics metrics = getResources().getDisplayMetrics();
		int width = metrics.widthPixels;

		int widthImage = width
				- 2
				* (getResources()
						.getDimensionPixelOffset(R.dimen.item_video_padding));
		int heightImage = (width * 67) / 100;

		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				widthImage, heightImage);

		int marginPager = getResources().getDimensionPixelOffset(
				R.dimen.item_video_padding);
		params.setMargins(marginPager, 0, marginPager, 0);
		viewPager.setLayoutParams(params);

		gvVideo = (CustomGridView) findViewById(R.id.gvVideo);
		tvTitleVideo = (TextView) findViewById(R.id.tvTitleVideo);
		tvTitleVideo.setVisibility(View.VISIBLE);
		llListCat = (LinearLayout) findViewById(R.id.llCate);

		scroller = (ScrollView) findViewById(R.id.index_layout_scroller);

		rlContainPager = (RelativeLayout) findViewById(R.id.index_layout_viewpager);
		
		// pase json video ///////////////////////////////////////////
		
		adapterVideo = new VideoIndexFragmentAdapter(IndexNoTabActivity.this,
				imageLoadern, optionsn);
		gvVideo.setAdapter(adapterVideo);
		adapterVideo.setData(DbSupport.getCache(TableDb.VIDEO));

		// pase json side//////////////////////////////////////

		adapterAds = new SlideShowImageAdapter(IndexNoTabActivity.this,
				imageLoader, options);

		viewPager.setAdapter(adapterAds);
		adapterAds.setData(DbSupport.getCache(TableDb.SLIDE));
		
		// pase json album ////////////////////////////////////////
		
		 vListCat = mInflater.inflate(
				R.layout.layout_item_cat_index, null);

		 tvTitle = (TextView) vListCat
				.findViewById(R.id.tvTitlePla);

		gvListCat = (CustomGridView) vListCat
				.findViewById(R.id.gvAlbum);

		adapterAlbum = new AlbumIndexFragmentAdapter(IndexNoTabActivity.this,
				imageLoader, options);
		gvListCat.setAdapter(adapterAlbum);
		adapterAlbum.setData(DbSupport.getCache(TableDb.ALBUM));
//		llListCat.addView(vListCat, adapterAlbum.getCount());
		
		adapterAlbum.setClickPla(new IClickPla() {

			@Override
			public void clickItemPla(String id) {
				Bundle b = new Bundle();

				b.putString(E4KidsConfig.KEY_INTENT_AID, id);
				gotoActivity(ListVideoByPlaActivity.class,
						b);
				app.setCatID(Integer.valueOf(id));
			}
		});

		
		adapterAds.setOnClickItemListener(new setOnClickItemListener() {

			@Override
			public void onCallClick(boolean isPla, String vid, String linkVideo) {
				Debug.debug("IsPlay : " + isPla + "\nID : " + vid);
				if (isPla) {
					Bundle bundle = new Bundle();
					bundle.putString(E4KidsConfig.KEY_INTENT_AID, vid);

					gotoActivity(ListVideoByPlaActivity.class, bundle);
				} else {
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
							.parse("http://m.youtube.com/watch?v=" + linkVideo));
					startActivity(intent);
				}
			}

		});
		  
		  adapterVideo.setIclickItemVideo(new ClickItemVideo() {

		    @Override
		    public void clickItem(String vid, String id) {
//			Bundle bundle = new Bundle();
//			bundle.putString(E4KidsConfig.KEY_INTENT_VID, vid);
//			bundle.putString(E4KidsConfig.KEY_INTENT_LINK, id);
//			
//			gotoActivity(PlayVideoYoutbe.class, bundle);
		    	Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.youtube.com/watch?v=" +id));
				startActivity(intent);
		    }
		});
		pageViewPager = 0;
		updateUI();

		// viewPager.setOnPageChangeListener(this);

		viewPager.setOnTouchListener(onSlideTouch);
		RequestService.rqHomeIndex(packageName, new RequestHome());

	}

	public static boolean showAdmod() {
		AdRequest adRequest = new AdRequest.Builder()
				.addTestDevice(AdRequest.DEVICE_ID_EMULATOR).addTestDevice("")
				.build();

		adView.loadAd(adRequest);
		return true;
	}

	/** Event to handle slide-show when user on touch */
	private OnTouchListener onSlideTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_MOVE:
				isTouch = true;
				// Remove runnable when moving
				slideHandler.removeCallbacks(mRunnable);
				break;
			case MotionEvent.ACTION_UP:
				isTouch = false;
				// Repost thread
				slideHandler.postDelayed(mRunnable, 2000);
				break;

			}
			return false;
		}
	};

	/** Runnable to auto sliding */
	private Runnable mRunnable = new Runnable() {
		@Override
		public void run() {
			if (!isTouch) {
				pageViewPager += 1;
				if (pageViewPager == adapterAds.getCount()) {
					pageViewPager = 0;
				}
				viewPager.setCurrentItem(pageViewPager, true);
			}
			slideHandler.postDelayed(mRunnable, 3000);
		}
	};

	private void updateUI() {
		new Handler().postDelayed(mRunnable, 3000);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		adapterVideo = new VideoIndexFragmentAdapter(IndexNoTabActivity.this,
				imageLoadern, optionsn);
		gvVideo.setAdapter(adapterVideo);
		adapterVideo.setData(DbSupport.getCache(TableDb.VIDEO));
	}

	private class RequestHome extends AbsRequestHandler {
		private InfoAds infoAds;

		@Override
		public void onWait(BzydroidHttpClient arg0) {
			super.onWait(arg0);
		}

		@Override
		public void onStarted(BzydroidHttpClient arg0) {
			super.onStarted(arg0);
			BzydroidLog.debug("onStarted");
		}

		@Override
		public void onSuccess(BzydroidHttpClient arg0, NetworkResponse arg1) {
			NetConfig config = new NetConfig.Builder().build();
			BaseNetSupportBeta.getInstance().init(config);
			HttpJSONObjectResponse jsonObjectResponse = (HttpJSONObjectResponse) arg0
					.getResponse();

			try {
				JSONObject object = jsonObjectResponse.toJSONObject();

				Debug.debug("Du lieu Response : " + object.toString());

				JSONObject jObjData = object
						.getJSONObject(E4KidsConfig.KEY_DATA);

				int code = jObjData.getInt(E4KidsConfig.KEY_CODE);

				if (code == 1) {
					LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

					JSONArray jArrAds = jObjData
							.getJSONArray(E4KidsConfig.Home.KEY_ADS);
					ArrayList<BaseObject> ojsilde = JsonSupport
							.jsonArray2BaseOj(jArrAds);
					DbSupport.saveCache(ojsilde, TableDb.SLIDE);
					adapterAds.setData(DbSupport.convertOj(ojsilde));

					JSONArray jArrVideo = jObjData
							.getJSONArray(E4KidsConfig.Home.KEY_VIDEO);

					ArrayList<BaseObject> ojmoi = JsonSupport
							.jsonArray2BaseOj(jArrVideo);
					DbSupport.saveCache(ojmoi, TableDb.VIDEO);
					adapterVideo.setData(DbSupport.convertOj(ojmoi));

					JSONArray jArrCats = jObjData
							.getJSONArray(E4KidsConfig.Home.KEY_CAT);
					int lengthCat = jArrCats.length();

					// Fill List cat
					if (lengthCat <= 0) {
						llListCat.setVisibility(View.GONE);
					} else {
						llListCat.setVisibility(View.VISIBLE);
						for (int i = 0; i < lengthCat; i++) {
							JSONObject objectLstCat = jArrCats.getJSONObject(i);

							String catTitle = objectLstCat.getString("title");

						
							tvTitle.setText(catTitle);

							JSONArray jArrDetailCat = objectLstCat
									.getJSONArray("playlists");
							ArrayList<BaseObject> ojalbum = JsonSupport
									.jsonArray2BaseOj(jArrDetailCat);
							DbSupport.saveCache(ojalbum, TableDb.ALBUM);
							adapterAlbum.setData(DbSupport.convertOj(ojalbum));
//							dataPlaylist = new ArrayList<InfoAlbum>();
//
//							int lengthDetailCat = jArrDetailCat.length();
//
//							for (int j = 0; j < lengthDetailCat; j++) {
//								//
//
//								JSONObject jObjDetaiCat = jArrDetailCat
//										.getJSONObject(j);
//
//								Debug.debug("Chi tiet Album trong Cat : " + i
//										+ " : " + jObjDetaiCat.toString());
//
//								InfoAlbum infoAlbum = parseJsonPla(
//										jObjDetaiCat, "");
//
//								dataPlaylist.add(infoAlbum);
//							}
//
//							gvListCat.setAdapter(adapterAlbum);

							
//							llListCat.addView(vListCat, i);
						}
					}

					scroller.setVisibility(View.VISIBLE);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onError(BzydroidHttpClient arg0,
				BzydroidNetworkExeception arg1) {
			super.onError(arg0, arg1);
			BzydroidLog.debug("onError");
		}

		@Override
		public void onFinished(BzydroidHttpClient arg0) {
			super.onFinished(arg0);
			BzydroidLog.debug("onFinished");
		}

	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		finish();
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.iv_search:
			if (llContainEdt.getVisibility() == View.GONE) {
				llContainEdt.setVisibility(View.VISIBLE);
				ivABSearch.setVisibility(View.GONE);
				tvABTitle.setVisibility(View.GONE);
				edtABSearch.setFocusable(true);
				edtABSearch.requestFocus();
				showBoard(edtABSearch);
			}
			break;
		case R.id.iv_cancel:
			String text = edtABSearch.getText().toString().trim();
			if (!text.equals("")) {
				edtABSearch.setText("");
			} else {
				llContainEdt.setVisibility(View.GONE);
				ivABSearch.setVisibility(View.VISIBLE);
				tvABTitle.setVisibility(View.VISIBLE);
				edtABSearch.setFocusable(true);
				hiddenBoard(edtABSearch);
			}
			break;

		}

	}
}
